package com.mlm.mlmapp.activity;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by Administrator on 2016/4/20 0020.
 */
public class DownloadBroadCast extends BroadcastReceiver {
    @Override
    @SuppressLint("NewApi")
    public void onReceive(Context context, Intent intent) {
        Log.d("sort", "DownloadBroadCast");
        if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())) {
            Toast.makeText(context, "正在下载，请稍后", Toast.LENGTH_SHORT).show();
            return;

        }
        long myDwonloadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

        SharedPreferences sPreferences = context.getSharedPreferences("Prefs", 0);

        long refernece = Long.valueOf(sPreferences.getString("downloadID", "0"));

        if (refernece == myDwonloadID) {
            Toast.makeText(context, "下载成功，准备安装", Toast.LENGTH_SHORT).show();

            Intent install = new Intent(Intent.ACTION_VIEW);

            Uri downloadFileUri = Uri.parse(sPreferences.getString("downloadUri", "0"));
            if (downloadFileUri != null) {

                install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");

                install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                context.startActivity(install);
            }else {
                Toast.makeText(context, "下载失败，请重新下载", Toast.LENGTH_SHORT).show();
            }
        }

    }
}
